﻿using System;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Text;

namespace gt.framework.standard.Cache
{
    public sealed class CacheManager
    {
        private static ObjectCache m_cache = MemoryCache.Default;

        public static T Get<T>(string key)
        {
            return (T)m_cache.Get(key);
        }

        public static void Insert<T>(string key, T obj, TimeSpan? expiredTime = null, List<string> dependencyFiles = null, OnChangedCallback changedCallback = null)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            if (expiredTime != null)
                policy.SlidingExpiration = expiredTime.Value;

            // 这里先加入缓存再加监视的原因是：在缓存加入时，也会触发监视事件，会导致出错。
            Insert<T>(key, obj, policy);

            if (dependencyFiles != null && dependencyFiles.Count != 0)
            {
                HostFileChangeMonitor monitor = new HostFileChangeMonitor(dependencyFiles);
                policy.ChangeMonitors.Add(monitor);
                monitor.NotifyOnChanged(changedCallback);
            }
        }

        public static void Insert<T>(string key, T obj, CacheItemPolicy policy)
        {
            m_cache.Set(key, obj, policy);
        }

        public static void Remove(string key)
        {
            m_cache.Remove(key);
        }

        public static bool Contains(string key)
        {
            return m_cache.Contains(key);
        }
    }
}
